package com.sanjiahantang.youjiarole.module.common.views.impl;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.sanjiahantang.youjiarole.R;
import com.sanjiahantang.youjiarole.base.BaseMvpActivity;
import com.sanjiahantang.youjiarole.base.BaseView;
import com.sanjiahantang.youjiarole.config.ConfigValue;
import com.sanjiahantang.youjiarole.module.common.beans.HelpBean;
import com.sanjiahantang.youjiarole.module.common.beans.RichTextBean;
import com.sanjiahantang.youjiarole.module.common.presenters.WebPresenter;


public class WebActivity extends BaseMvpActivity<BaseView, WebPresenter> implements View.OnClickListener, BaseView {

    private WebView webView;
    private TextView title;

    @Override
    public WebPresenter initPresenter() {
        return new WebPresenter();
    }

    public void initView() {
        setContentView(R.layout.activity_web);
        title = (TextView) findViewById(R.id.title);
        webView = (WebView) findViewById(R.id.webView);
        setWebViewConfig();
        findViewById(R.id.fl_Left).setOnClickListener(this);
        int type = getIntent().getIntExtra(KEY_TYPE, 0);
        switch (type) {
            case WEB_TYPE_HELP:
                loadHelpContent();
                break;
            case WEB_TYPE_MATCH_CENTER:
                loadMatchCenterContent();
                break;
            case WEB_TYPE_MESSAGE:
                loadMessage();
                break;
            case WEB_TYPE_CONTRACT:
                loadContract();
                break;
            case WEB_TYPE_RICHTEXT:
                loadFRichTextContent();
                break;
            case WEB_TYPE_3D:
                load3D();
                break;
            default:
                webView.loadUrl(getIntent().getStringExtra("url"));
                title.setText("商品");
                break;
        }

    }

    private void load3D() {
        String url = getIntent().getStringExtra(KEY_PARAM);
        String titleStr = getIntent().getStringExtra(KEY_TITLE);
        if (!TextUtils.isEmpty(titleStr)){
            title.setText(titleStr);
        }

        if (!TextUtils.isEmpty(url) && url.length() > "http".length() && url.indexOf("http") == 0){
            webView.loadUrl(url);
        }else {
            webView.loadDataWithBaseURL(null, url, "text/html", "UTF-8", null);
        }

    }

    private void loadContract() {

        title.setText("合同");
        findViewById(R.id.fl_Left).setVisibility(View.GONE);
        String url = ConfigValue.API_URL + "/sign/createContract";
        String param = getIntent().getStringExtra(KEY_PARAM);
        if (!TextUtils.isEmpty(param)) {

            webView.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    if (url.contains("suceess=200")) {
                        webView.setVisibility(View.GONE);
                        setResult(RESULT_OK, getIntent());
                        finish();
                        return true;
                    }
                    return super.shouldOverrideUrlLoading(view, url);
                }

                @Override
                public void onLoadResource(WebView view, String url) {
                    if (url.contains("suceess=200")) {
                        webView.setVisibility(View.GONE);
                        setResult(RESULT_OK, getIntent());
                        finish();
                        return;
                    }
                    super.onLoadResource(view, url);
                }

            });
            webView.postUrl(url, param.getBytes());
        }

    }

    private void loadMessage() {
        String noticeContent = getIntent().getStringExtra(KEY_NOTICE_CONTENT);
        Log.e("内容", noticeContent);
        webView.loadDataWithBaseURL(null, noticeContent, "text/html", "UTF-8", null);
        title.setText("消息中心");
    }

    private void loadMatchCenterContent() {
        int id = getIntent().getIntExtra(KEY_ID, 0);
        String articleTitle = getIntent().getStringExtra(KEY_TITLE);
        webView.getSettings().setDefaultFontSize(16);
        title.setText(articleTitle == null ? "培训中心" : articleTitle);
        presenter.loadMatchCenterArticle($this, id, new OnLoadListener() {

            @Override
            public void onLoad(Object content) {
                HelpBean.Item item = (HelpBean.Item) content;
                String head = "<style>img{width:100%;}</style>";
                webView.loadDataWithBaseURL(null, head + item.getArContent(), "text/html", "UTF-8", null);
                title.setText(item.getArTitle());
            }
        });
    }

    //富文本
    private void loadFRichTextContent() {
        String id = getIntent().getStringExtra(KEY_ID);
        title.setText(getIntent().getStringExtra(KEY_TITLE));
        presenter.loadRichTextCenterArticle($this, id, new OnLoadListener() {

            @Override
            public void onLoad(Object content) {
                RichTextBean.Item bean = (RichTextBean.Item) content;
                webView.loadDataWithBaseURL(null, bean.getContent(), "text/html", "UTF-8", null);
            }
        });
    }

    @Override
    public void initData() {

    }

    private void loadHelpContent() {
        int id = getIntent().getIntExtra(KEY_ID, 0);
        String articleTitle = getIntent().getStringExtra(KEY_TITLE);
        title.setText(articleTitle == null ? "帮助中心" : articleTitle);
        presenter.loadHelpArticle($this, id, new OnLoadListener() {

            @Override
            public void onLoad(Object content) {
                webView.loadDataWithBaseURL(null, (String) content, "text/html", "UTF-8", null);
            }
        });
    }

    private void setWebViewConfig() {
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);//启用js
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//js和android交互
        settings.setAllowFileAccess(true); // 允许访问文件
        settings.setAppCacheEnabled(true); //设置H5的缓存打开,默认关闭
//        settings.setUseWideViewPort(true);//设置webview自适应屏幕大小
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);//设置，可能的话使所有列的宽度不超过屏幕宽度
        settings.setLoadWithOverviewMode(true);//设置webview自适应屏幕大小
        settings.setDomStorageEnabled(true);//设置可以使用localStorage
        settings.setSupportZoom(false);//关闭zoom按钮
        settings.setBuiltInZoomControls(false);//关闭zoom

        //启用数据库
        settings.setDatabaseEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(settings.MIXED_CONTENT_ALWAYS_ALLOW);  //注意安卓5.0以上的权限
        }
        webView.setWebViewClient(new InnerWebViewClient());
        webView.setWebChromeClient(new InnerChromeClient());
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fl_Left:
                finish();
                break;
        }
    }

    @Override
    public void showProgress() {
        super.showProgress($this);
    }

    //Web视图
    private class InnerWebViewClient extends WebViewClient {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }
    private class InnerChromeClient extends WebChromeClient {

        @Override
        public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {

            AlertDialog.Builder b2 = new AlertDialog.Builder($this)
                    .setTitle("提示").setMessage(message)
                    .setPositiveButton("ok",
                            new AlertDialog.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // TODO Auto-generated method stub
                                    result.confirm();
                                }
                            });

            b2.setCancelable(false);
            b2.create();
            b2.show();
            return true;
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            // TODO Auto-generated method stub
            return super.onJsConfirm(view, url, message, result);
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
                JsPromptResult result) {
            // TODO Auto-generated method stub
            return super.onJsPrompt(view, url, message, defaultValue, result);
        }

    }

    public static void open3DUrl(Context context, String remark, String title) {
        context.startActivity(new Intent(context,WebActivity.class)
                .putExtra(KEY_TYPE,WEB_TYPE_3D)
                .putExtra(KEY_PARAM,remark).putExtra(KEY_TITLE,title));
    }
}
